package com.lumeijin.repository;

import com.lumeijin.entity.SmsCode;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Repository
public interface SmsCodeRepository extends JpaRepository<SmsCode, Long> {
    
    @Query("SELECT s FROM SmsCode s WHERE s.phone = :phone AND s.code = :code AND s.isUsed = false AND s.expiredTime > :now ORDER BY s.createdTime DESC")
    Optional<SmsCode> findValidCodeByPhoneAndCode(@Param("phone") String phone, @Param("code") String code, @Param("now") LocalDateTime now);
    
    @Query("SELECT s FROM SmsCode s WHERE s.phone = :phone ORDER BY s.createdTime DESC")
    List<SmsCode> findByPhoneOrderByCreatedTimeDesc(@Param("phone") String phone);
    
    @Modifying
    @Transactional
    @Query("UPDATE SmsCode s SET s.isUsed = true WHERE s.phone = :phone AND s.code = :code")
    void markCodeAsUsed(@Param("phone") String phone, @Param("code") String code);
    
    @Modifying
    @Transactional
    @Query("DELETE FROM SmsCode s WHERE s.expiredTime < :now")
    void deleteExpiredCodes(@Param("now") LocalDateTime now);
}
